﻿using System;
using ESRI.ArcGIS;
using ESRI.ArcGIS.esriSystem;

namespace DllShepherd.Core.Esri
{
    public class EsriInitilization
    {
        private static bool _isStarted = false;

        public static void Start()
        {
            if (_isStarted)
                return;

            if (!Initialize(ProductCode.Server, esriLicenseProductCode.esriLicenseProductCodeArcServer))
            {
                if (!Initialize(ProductCode.Engine, esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB))
                {
                    throw new ApplicationException(
                        "Unable to bind to ArcGIS license Server nor to Engine. Please check your licenses.");
                }
            }
            _isStarted = true;
        }

        private static bool Initialize(ProductCode product, esriLicenseProductCode esriLicenseProduct)
        {
            if (RuntimeManager.Bind(product))
            {
                IAoInitialize aoInit = new AoInitializeClass();
                aoInit.Initialize(esriLicenseProduct);
                return true;
            }
            return false;
        }

        public static void ReInitialize()
        {
            IAoInitialize pArcObjsInitialize = new AoInitializeClass();

            var esriLicenseStatus = pArcObjsInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

            if (esriLicenseStatus == esriLicenseStatus.esriLicenseUnavailable || esriLicenseStatus == esriLicenseStatus.esriLicenseNotLicensed)
            {
                esriLicenseStatus = pArcObjsInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeEngineGeoDB);
                if (esriLicenseStatus == esriLicenseStatus.esriLicenseUnavailable || esriLicenseStatus == esriLicenseStatus.esriLicenseNotLicensed)
                {
                    throw new ApplicationException(
                        "Unable to bind to ArcGIS license Server nor to Engine. Please check your licenses.");
                }
            }
        }
    }
}
